1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/*!
Dynamic terms, which allow run-time extension of `isotope`, mainly for testing and debugging purposes
*/
use super::*;

/// The interface which must be implemented by dynamic terms
///
/// Rather than implement this manually, it is usually preferable to implement
/// `Value`, which will implement this trait automatically assuming the type
/// also satisfies `Debug`, `Hash`, `PartialEq`, and `'static`.
pub trait DynamicValue: Debug + Any + DynHash {
    /// Cons this term within a given context. Return `None` if already consed.
    fn dyn_cons(&self, ctx: &mut dyn ConsCtx) -> Option<TermId>;
    /// Get the type annotation of this term
    fn dyn_ty(&self) -> Option<AnnotationRef>;
    /// Get the index of this term in an `isotope` program graph, if any
    fn dyn_ix(&self) -> Option<NodeIx>;
    /// Get the hash-code of this term
    fn dyn_code(&self) -> Code;
    /// Get whether this term is a type
    fn dyn_is_local_ty(&self) -> Option<bool>;
    /// Get whether this term is a universe
    fn dyn_is_local_universe(&self) -> Option<bool>;
    /// Get whether this term is in "root form"
    fn dyn_is_root(&self) -> bool;
    /// Get whether this term is a subtype of another term in a given context
    fn dyn_is_subtype_in(&self, other: &Term, ctx: &mut dyn TermEqCtxMut) -> Option<bool>;
    /// Get whether this term has a universe *in all contexts*
    fn dyn_universe(&self) -> Option<Universe>;
    /// Get the untyped hash-code of this term
    fn dyn_untyped_code(&self) -> Code;
    /// Get the variable filter of this term
    fn dyn_filter(&self) -> VarFilter;
    /// Shift this term's variables with index `>= base` up by `n` in a given context
    fn dyn_shift(&self, n: i32, base: u32, ctx: &mut dyn ConsCtx) -> Result<Option<TermId>, Error>;
    /// Whether this term has a given variable dependency
    fn dyn_has_var_dep(&self, ix: u32, equiv: bool) -> bool;
    /// Whether this term has a given variable dependency below `ix` and above `base`
    fn dyn_has_dep_below(&self, ix: u32, base: u32) -> bool;
    /// Load this term's flags
    fn dyn_load_flags(&self) -> TyckFlags;
    /// Set this term's flags
    fn dyn_set_flags(&self, flags: TyckFlags);
    /// Compare this term to another
    #[inline]
    fn dyn_eq_term_in(&self, other: &Term, ctx: &mut dyn TermEqCtxMut) -> Option<bool> {
        match other {
            Term::Dynamic(other) => self.dyn_eq_in(&*other.0, ctx),
            _ => Some(false),
        }
    }
    /// Compare this term to a term ID
    #[inline]
    fn dyn_eq_id_in(&self, other: &TermId, ctx: &mut dyn TermEqCtxMut) -> Option<bool> {
        self.dyn_eq_term_in(&**other, ctx)
    }
    /// Compare this term to another dynamic term
    fn dyn_eq_in(&self, other: &dyn DynamicValue, ctx: &mut dyn TermEqCtxMut) -> Option<bool>;
    /// Convert this term to an `Any`
    fn as_any(&self) -> &dyn Any;
}

impl<V: Value + PartialEq + Debug + Hash + 'static> DynamicValue for V {
    fn dyn_cons(&self, ctx: &mut dyn ConsCtx) -> Option<TermId> {
        self.cons_id(ctx)
    }

    fn dyn_ty(&self) -> Option<AnnotationRef> {
        self.annot()
    }

    fn dyn_ix(&self) -> Option<NodeIx> {
        self.id()
    }

    fn dyn_code(&self) -> Code {
        self.code()
    }

    fn dyn_is_local_ty(&self) -> Option<bool> {
        self.is_local_ty()
    }

    fn dyn_is_local_universe(&self) -> Option<bool> {
        self.is_local_universe()
    }

    fn dyn_is_root(&self) -> bool {
        self.is_root()
    }

    fn dyn_is_subtype_in(&self, other: &Term, ctx: &mut dyn TermEqCtxMut) -> Option<bool> {
        self.is_subtype_in(other, ctx)
    }

    fn dyn_universe(&self) -> Option<Universe> {
        self.universe()
    }

    fn dyn_untyped_code(&self) -> Code {
        self.untyped_code()
    }

    fn dyn_filter(&self) -> VarFilter {
        self.get_filter()
    }

    fn dyn_shift(&self, n: i32, base: u32, ctx: &mut dyn ConsCtx) -> Result<Option<TermId>, Error> {
        self.shift_id(n, base, ctx)
    }

    fn dyn_has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.has_var_dep(ix, equiv)
    }

    fn dyn_has_dep_below(&self, ix: u32, base: u32) -> bool {
        self.has_dep_below(ix, base)
    }

    fn dyn_load_flags(&self) -> TyckFlags {
        self.load_flags()
    }

    fn dyn_set_flags(&self, flags: TyckFlags) {
        self.set_flags(flags)
    }

    fn dyn_eq_in(&self, other: &dyn DynamicValue, ctx: &mut dyn TermEqCtxMut) -> Option<bool> {
        if let Some(other) = other.as_any().downcast_ref::<V>() {
            self.eq_in(other, ctx)
        } else {
            Some(false)
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A dynamic version of the hash trait
///
/// Implemented automatically for all `Hash` types.
pub trait DynHash {
    /// Hash this using a given hasher
    fn dyn_hash(&self, state: &mut dyn Hasher);
}

impl<H: Hash + ?Sized> DynHash for H {
    fn dyn_hash(&self, mut state: &mut dyn Hasher) {
        self.hash(&mut state);
    }
}

/// A dynamic term
#[derive(Debug, Clone)]
pub struct DynamicTerm(pub Arc<dyn DynamicValue + Send + Sync>);

impl Deref for DynamicTerm {
    type Target = dyn DynamicValue + Send + Sync;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl Cons for DynamicTerm {
    type Consed = TermId;

    #[inline]
    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        self.cons_id(ctx)
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        //TODO: think about this...
        self.into_id_direct()
    }
}

impl Substitute for DynamicTerm {
    type Substituted = TermId;

    #[inline]
    fn subst_rec(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<TermId>, Error> {
        self.subst_id(ctx)
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl Typecheck for DynamicTerm {
    #[inline]
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        //TODO: this
        false
    }

    #[inline]
    fn do_global_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        //TODO: this
        Some(false)
    }

    #[inline]
    fn do_annot_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        //TODO: this
        Some(false)
    }

    #[inline]
    fn tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        //TODO: this
        Some(false)
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.0.dyn_load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.0.dyn_set_flags(flags)
    }
}

impl HasDependencies for DynamicTerm {
    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.0.dyn_has_var_dep(ix, equiv)
    }

    #[inline]
    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        self.0.dyn_has_dep_below(ix, base)
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.0.dyn_filter()
    }
}

impl TermEq for DynamicTerm {
    #[inline]
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.0.dyn_eq_in(other, ctx.as_dyn_eq_mut())
    }
}

impl Value for DynamicTerm {
    type ValueConsed = TermId;
    type ValueSubstituted = TermId;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Dynamic(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        self.0.dyn_ty()
    }

    #[inline]
    fn id(&self) -> Option<NodeIx> {
        self.0.dyn_ix()
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        self.0.dyn_is_local_ty()
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        self.0.dyn_is_local_universe()
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        //TODO: this
        None
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        //TODO: this
        None
    }

    #[inline]
    fn is_root(&self) -> bool {
        self.0.dyn_is_root()
    }

    #[inline]
    fn coerce(
        &self,
        _ty: Option<TermId>,
        _ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        Err(Error::NotImplemented)
    }

    #[inline]
    fn annotate_unchecked(
        &self,
        _annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        Err(Error::NotImplemented)
    }

    #[inline]
    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.0.dyn_is_subtype_in(other, ctx.as_dyn_eq_mut())
    }

    #[inline]
    fn universe(&self) -> Option<Universe> {
        self.0.dyn_universe()
    }

    #[inline]
    fn code(&self) -> Code {
        self.0.dyn_code()
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        self.0.dyn_untyped_code()
    }

    #[inline]
    fn subst_id(&self, _ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<TermId>, Error> {
        //TODO: this
        Err(Error::NotImplemented)
    }

    #[inline]
    fn shift_id(
        &self,
        n: i32,
        base: u32,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        self.0.dyn_shift(n, base, ctx.as_dyn_cons_mut())
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.0.dyn_eq_term_in(other, ctx.as_dyn_eq_mut())
    }

    #[inline]
    fn eq_id_in(&self, other: &TermId, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.0.dyn_eq_id_in(other, ctx.as_dyn_eq_mut())
    }

    #[inline]
    fn cons_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<TermId> {
        self.0.dyn_cons(ctx.as_dyn_cons_mut())
    }

    #[inline]
    fn apply(
        &self,
        _args: &mut SmallVec<[TermId; 2]>,
        _ctx: &mut (impl EvalCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        Err(Error::NotImplemented)
    }

    //TODO: this...
    #[inline]
    fn form(&self) -> Form {
        Form::BetaEta
    }
}

impl PartialEq for DynamicTerm {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
            || self
                .0
                .dyn_eq_in(&*other.0, &mut Structural)
                .unwrap_or(false)
    }
}

impl PartialEq<TermId> for DynamicTerm {
    fn eq(&self, other: &TermId) -> bool {
        self.0.dyn_eq_id_in(other, &mut Structural).unwrap_or(false)
    }
}

impl PartialEq<Term> for DynamicTerm {
    fn eq(&self, other: &Term) -> bool {
        self.0
            .dyn_eq_term_in(other, &mut Structural)
            .unwrap_or(false)
    }
}

impl Eq for DynamicTerm {}

impl Hash for DynamicTerm {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.dyn_hash(state)
    }
}

/// A debug value with an arbitrary code, type, and name, which dynamically compares by pointer
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct DebugValue {
    /// The name of this debug value
    pub name: String,
    /// The code of this debug value
    pub code: Code,
    /// This value's flags
    pub flags: TyckFlags,
}

impl DebugValue {
    /// Create a new debug value with a given code
    #[inline]
    pub fn code(name: impl Into<String>, code: Code) -> DebugValue {
        DebugValue {
            name: name.into(),
            code,
            flags: TyckFlags::default(),
        }
    }
    /// Create a new debug value with a given name
    #[inline]
    pub fn name(name: impl Into<String>) -> DebugValue {
        let name = name.into();
        let code = Code(fxhash::hash64(&name));
        DebugValue {
            name,
            code,
            flags: TyckFlags::default(),
        }
    }
    /// Create a new debug value `TermId` with a given code
    #[inline]
    pub fn code_id(name: impl Into<String>, code: Code) -> TermId {
        Self::code(name, code).into_id()
    }
    /// Create a new debug value `TermId` with a given name
    #[inline]
    pub fn name_id(name: impl Into<String>) -> TermId {
        Self::name(name).into_id()
    }
    /// Convert this `DebugValue` to a `DynamicTerm`
    #[inline]
    pub fn into_dyn_term(self) -> DynamicTerm {
        DynamicTerm(Arc::new(self))
    }
    /// Convert this `DebugValue` to a `Term`
    #[inline]
    pub fn into_term(self) -> Term {
        Term::Dynamic(self.into_dyn_term())
    }
    /// Convert this `DebugValue` to a `TermId`
    #[inline]
    pub fn into_id(self) -> TermId {
        self.into_dyn_term().into_id_direct()
    }
}

impl Cons for DebugValue {
    type Consed = DebugValue;

    fn cons(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        None
    }

    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for DebugValue {
    type Substituted = DebugValue;

    fn subst_rec(&self, _ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<DebugValue>, Error> {
        Ok(None)
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl Typecheck for DebugValue {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        false
    }

    fn do_global_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(false)
    }

    fn do_annot_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(false)
    }

    fn tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(false)
    }

    fn load_flags(&self) -> TyckFlags {
        self.flags
    }

    fn set_flags(&self, _flags: TyckFlags) {}
}

impl HasDependencies for DebugValue {
    fn has_var_dep(&self, _ix: u32, _equiv: bool) -> bool {
        false
    }

    fn has_dep_below(&self, _ix: u32, _base: u32) -> bool {
        false
    }

    fn get_filter(&self) -> VarFilter {
        VarFilter::EMPTY
    }
}

impl TermEq for DebugValue {
    fn eq_in(&self, other: &Self, _ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if self.name == other.name {
            Some(true)
        } else {
            None
        }
    }
}

impl Value for DebugValue {
    type ValueConsed = DebugValue;

    type ValueSubstituted = DebugValue;

    fn into_term_direct(self) -> Term {
        Term::Dynamic(self.into_dyn_term())
    }

    fn annot(&self) -> Option<AnnotationRef> {
        None
    }

    fn id(&self) -> Option<NodeIx> {
        None
    }

    fn is_local_ty(&self) -> Option<bool> {
        Some(false)
    }

    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    fn is_root(&self) -> bool {
        true
    }

    fn coerce(
        &self,
        _ty: Option<TermId>,
        _ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<DebugValue>, Error> {
        Err(Error::CoerceUntyped)
    }

    fn annotate_unchecked(
        &self,
        _annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<DebugValue>, Error> {
        Err(Error::CoerceUntyped)
    }

    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.eq_term_in(other, ctx)
    }

    fn universe(&self) -> Option<Universe> {
        None
    }

    fn code(&self) -> Code {
        self.code
    }

    fn untyped_code(&self) -> Code {
        self.code
    }

    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Dynamic(other) => self.dyn_eq_in(other, ctx.as_dyn_eq_mut()),
            _ => Some(false),
        }
    }

    fn apply(
        &self,
        _args: &mut SmallVec<[TermId; 2]>,
        _ctx: &mut (impl EvalCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        Ok(None)
    }

    fn form(&self) -> Form {
        Form::BetaEta
    }
}

impl PartialEq<Term> for DebugValue {
    fn eq(&self, other: &Term) -> bool {
        self.eq_term_in(other, &mut Structural).unwrap_or(false)
    }
}

impl PartialEq<TermId> for DebugValue {
    fn eq(&self, other: &TermId) -> bool {
        self.eq(&**other)
    }
}